/*
 * @author hzq
 * @date 2024-12-04 19:41:44
 * @description requestAnimationFrame
 * @see 🚀
 * @status done
 */

/**
 * 定义requestAnimationFrame函数，用于在下次重绘之前执行回调函数
 * @returns {requestAnimationFrame: Function, cancelAnimationFrame: Function}
 */
const fn = (): {
  requestAnimationFrame: Function
  cancelAnimationFrame: Function
} => {
  let lastTime = 0
  let requestAnimationFrame: any
  let cancelAnimationFrame: any
  const isSevicer = typeof window === 'undefined'
  if (isSevicer) {
    requestAnimationFrame = function () {
      return
    }
    cancelAnimationFrame = function () {
      return
    }
  } else {
    requestAnimationFrame = window.requestAnimationFrame
    cancelAnimationFrame = window.cancelAnimationFrame
    if (!requestAnimationFrame || !cancelAnimationFrame) {
      // 定义requestAnimationFrame函数，用于在下次重绘之前执行回调函数
      requestAnimationFrame = function (callback: Function) {
        // 获取当前时间
        const currTime = new Date().getTime()
        // 计算距离下次重绘的时间
        const timeToCall = Math.max(0, 16 - (currTime - lastTime))
        // 设置定时器，在距离下次重绘的时间后执行回调函数
        const id = window.setTimeout(function () {
          callback(currTime + timeToCall)
        }, timeToCall)
        // 更新上次重绘的时间
        lastTime = currTime + timeToCall
        // 返回定时器的id
        return id
      }
      // 定义cancelAnimationFrame函数，用于取消重绘
      cancelAnimationFrame = function (id: number) {
        // 清除定时器
        window.clearTimeout(id)
      }
    }
  }
  return { requestAnimationFrame, cancelAnimationFrame }
}

export const { requestAnimationFrame, cancelAnimationFrame } = fn()
